import { message } from "antd";
import axios from "axios";

import { history } from "umi";

const http = axios.create();
http.defaults.timeout = 10000;

// 请求拦截
http.interceptors.request.use(
  async (config: any) => {
    const token = localStorage.getItem("token") || undefined;
    if (!token) history.replace("/login");
    config.headers["token"] = token;
    return config;
  },
  (error: any) => {
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// 响应拦截器
http.interceptors.response.use(
  (response) => {
    const res = response.data;

    if (res.code !== 0) message.error(res.msg);
    //登录失败
    if (res.code === 1002) {
      localStorage.clear();
      history.replace("/login");
    }

    return res;
  },
  (error) => {
    return Promise.reject(error);
  }
);

export default http;
